/**
 * 
 */
package com.agrec.client;

import java.util.Iterator;

import org.apache.jasper.tagplugins.jstl.ForEach;

import com.agrec.client.actors.CitiesNames;
import com.agrec.client.actors.CompaniesNames;
import com.agrec.client.actors.Name;
import com.agrec.client.services.KMRServiceAsync;
import com.agrec.client.services.UserServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;

/**
 * @author AlaA Gharbawi
 * Add a candidate Form
 *
 */
public class AddCandidateForm extends Composite {

	private static final int workedB4Limit = 5;
	private KMRServiceAsync kmrService;
	private FlexTable table, collapableTable;
	private AGRecTextBox fNameTB, lNameTB, jobTitleTB, 
		mobileTB, emailTB;
	private AGRecTextBox workedB4TB[];private int companyCount = 1;
	private FlowPanel companyTBPanel;
	private Label NameL, statusL, companyL, jobTitleL, 
		workedB4L, contactsL, uploadL;
	private ListBox statusLB, countryLB;
	private Hyperlink addCompanyHL;
	private Button uploadB;
	// Define the oracle that finds suggestions
    private MultiWordSuggestOracle companyOracle;
    private MultiWordSuggestOracle cityOracle;
    

    // Create the suggest box
    private SuggestBox companySBox;
    private SuggestBox citySBox;
    
    private FormPanel uploadForm;
    private FileUpload fileUpload;
	
    private FlexCellFormatter tabelCellFormatter;
	private FlexCellFormatter collapableTableCellFormatter;
	
	private Button submit;
	
	
	@SuppressWarnings("deprecation")
	public AddCandidateForm(KMRServiceAsync kmrService) {
		this.kmrService = kmrService;
		
		
		table = new FlexTable();
		collapableTable = new FlexTable();
		collapableTable.setVisible(false);
		tabelCellFormatter = table.getFlexCellFormatter();
		collapableTableCellFormatter = collapableTable.getFlexCellFormatter();
		fNameTB = new AGRecTextBox("First Name");
		
		lNameTB = new AGRecTextBox("Last Name");
		
		jobTitleTB = new AGRecTextBox("Current Job Title"); 
		workedB4TB = new AGRecTextBox[workedB4Limit];
		for (int i = 0; i < workedB4TB.length; i++) {
			workedB4TB[i] = new AGRecTextBox("Previous Employer");
		}
		companyTBPanel = new FlowPanel();

		mobileTB = new AGRecTextBox("Enter Mobile");
		
		emailTB = new AGRecTextBox("Enter Email");
		
		uploadForm = new FormPanel();
		uploadForm.setAction(GWT.getModuleBaseURL() + "UploadFileServlet");
		
		// Because we're going to add a FileUpload widget, we'll need to set the
		// form to use the POST method, and multipart MIME encoding.
		uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
		uploadForm.setMethod(FormPanel.METHOD_POST); 
		uploadForm.addSubmitCompleteHandler(new SubmitCompleteHandler() {
			public void onSubmitComplete(SubmitCompleteEvent event) {
				Window.alert(event.getResults());
				
			}
		    }); 
		
		fileUpload = new FileUpload();
		fileUpload.setName("uploadFormElement"); 
		uploadB = new Button("Upload");
		uploadB.addClickHandler(new ClickHandler(){

			public void onClick(ClickEvent event) {
				String filename = fileUpload.getFilename();
		        if (filename.length() == 0) {
		        	Window.alert("Error");
		        } else {
		        	if(filename.endsWith(".doc") || filename.endsWith(".docx")){
		        		//Somehow upload the file here to DB
		        		uploadForm.submit();
		        	}
		        	else{
		        		Window.alert("Only accepts Word document format (.doc, or .docx)");
		        	}
		        	
		        }
				
			}});
		
		HorizontalPanel uploadPanel = new HorizontalPanel();
		
		uploadPanel.add(fileUpload);
		uploadPanel.add(uploadB);
		uploadForm.setWidget(uploadPanel);
		
		NameL = new Label("Your name");
		statusL = new Label("You are currently");
		companyL = new Label("Company");
		jobTitleL = new Label("Job title");
		workedB4L = new Label("Where you worked before");
		contactsL = new Label("Your contacts");
		uploadL = new Label("Upload CV");
		
		statusLB = new ListBox(false);
		statusLB.addChangeHandler(new ChangeHandler(){

			public void onChange(ChangeEvent event) {
				if (statusLB.getItemText(statusLB.getSelectedIndex()).equals("Employed")){
					collapableTable.setVisible(true);
				}else{
					collapableTable.setVisible(false);
				}
					
				
			}});
		//statusLB.addItem("Choose your work status", "");
		
		statusLB.addItem("Employed");
		collapableTable.setVisible(true);
		statusLB.addItem("Looking for work");
		statusLB.addItem("Working independent");
		statusLB.setSelectedIndex(0);
		
		countryLB = new ListBox(false);
		countryLB.addChangeHandler(new ChangeHandler(){

			public void onChange(ChangeEvent event) {
				setUpCityOracle();
				
			}});
		//should come from DB
		countryLB.addItem("Country", "");
		countryLB.addItem("Saudi Arabia");
		countryLB.addItem("---------------------","");
		countryLB.addItem("United Arab Emirates");
		countryLB.addItem("Qatar");
		countryLB.addItem("Bahrain");
		
		setUpCompanyOracle();
		setUpCityOracle();
		companySBox = new SuggestBox(companyOracle);
		companySBox.addStyleName("shadedText");
		companySBox.setText("Current Employer");
		companySBox.addClickListener(new ClickListener(){

			public void onClick(Widget sender) {
				if (companySBox.getText().equals("Current Employer")){
					companySBox.setText("");
					companySBox.removeStyleName("shadedText");
				}
				
			}});
		citySBox = new SuggestBox(cityOracle);
		citySBox.setText("City");
		citySBox.addStyleName("shadedText");
		citySBox.addClickListener(new ClickListener(){

			public void onClick(Widget sender) {
				if (citySBox.getText().equals("City")){
					citySBox.setText("");
					citySBox.removeStyleName("shadedText");
				}
				
			}});
		
		addCompanyHL = new Hyperlink("+ Add another company","");
		addCompanyHL.addClickHandler(new ClickHandler(){

			public void onClick(ClickEvent event) {
				if(companyCount < workedB4Limit){
					companyTBPanel.add(workedB4TB[companyCount]);
					companyCount++;
				}
				
			}});
		
		submit = new Button("Send to M.D.");
		submit.addClickHandler(new SubmitHandler());
		
		table.setWidget(0, 0, NameL);
		table.setWidget(0, 1, fNameTB);
		table.setWidget(0, 2, lNameTB);
		
		table.setWidget(1, 0, statusL);
		table.setWidget(1, 1, statusLB);
		
		collapableTable.setWidget(0, 0, companyL);
		collapableTable.setWidget(0, 1, companySBox);
		
		collapableTable.setWidget(1, 0, jobTitleL);
		collapableTable.setWidget(1, 1, jobTitleTB);
		
		table.setWidget(2, 0, collapableTable);
		tabelCellFormatter.setColSpan(2, 0, 3);
		
		table.setWidget(3, 0, workedB4L);
		companyTBPanel.add(workedB4TB[0]);
		table.setWidget(3, 1, companyTBPanel);
		table.setWidget(3, 2, addCompanyHL);
		
		table.setWidget(4, 0, contactsL);
		table.setWidget(4, 1, countryLB);
		table.setWidget(4, 2, citySBox);
		
		table.setWidget(5, 1, mobileTB);
		table.setWidget(5, 2, emailTB);
		
		table.setWidget(6, 0, uploadL);
		table.setWidget(6, 1, uploadForm);
		//table.setWidget(6, 1, fileUpload);
		//table.setWidget(6, 2, uploadB);
		
		table.setWidget(7, 0, submit);
		tabelCellFormatter.setRowSpan(7, 0, 3);
		
		
		DecoratorPanel decPanel = new DecoratorPanel();
    	decPanel.setWidget(table);
    	
    	initWidget(decPanel);
	}

	class SubmitHandler implements ClickHandler {

		private Name candidate;
		
		public void onClick(ClickEvent event) {
			
			
			if (valid())
				submit();
			else{
				
			}
			
		}

		private boolean valid() {
			boolean valid = true;
			candidate = new Name();
			candidate.firstName(fNameTB.getText());
			candidate.lastName(lNameTB.getText());
			candidate.status(statusLB.getValue(statusLB.getSelectedIndex()));
			candidate.companyName(companySBox.getText());
			candidate.title(jobTitleTB.getText());
			
			String tmp = "";
			for (int i = 0; i < workedB4TB.length; i++) {
				if(!workedB4TB[i].getText().equals(""))
					tmp+=workedB4TB[i].getText()+",";
			}
			candidate.previousEmployers(tmp);
			candidate.country(countryLB.getValue(countryLB.getSelectedIndex()));
			candidate.city(citySBox.getText());
			candidate.cellPhone(mobileTB.getText());
			candidate.email(emailTB.getText());
			candidate.cv(fileUpload.getFilename());
			
			
			if (candidate.firstName().equals("First Name") || candidate.firstName().trim().equals("") ){
				valid = false;
				fNameTB.addErrorStyleName("errorTextBox");
			}
			if (candidate.lastName().equals("Last Name") || candidate.lastName().trim().equals("") ){
				valid = false;
				lNameTB.addErrorStyleName("errorTextBox");
			}
			if (candidate.cellPhone().equals("Enter Mobile") || candidate.cellPhone().trim().equals("") ){
				valid = false;
				mobileTB.addErrorStyleName("errorTextBox");
			}
			
			if(candidate.status().equals("Employed")){
				//jobTitle and Employer
				if (candidate.title().equals("Current Job Title") || candidate.cellPhone().trim().equals("") ){
					valid = false;
					jobTitleTB.addErrorStyleName("errorTextBox");
				}
				if (candidate.companyName().equals("Current Employer") || candidate.cellPhone().trim().equals("") ){
					valid = false;
					companySBox.addStyleName("errorTextBox");
				}
			}
			else{
				//previous Employers, CV
				if (workedB4TB[0].getText().equals("Previous Employer") || workedB4TB[0].getText().trim().equals("") ){
					valid = false;
					workedB4TB[0].addErrorStyleName("errorTextBox");
				}
					
//				for (int i = 0; i < workedB4TB.length; i++) {
//					if (workedB4TB[i].getText().equals("Previous Employer") || workedB4TB[i].getText().trim().equals("") ){
//						valid = false;
//						workedB4TB[i].addErrorStyleName("errorTextBox");
//					}
//				}
					
				
//				if (candidate.cv().equals("Previous Employer") || candidate.cellPhone().trim().equals("") ){
//					valid = false;
//					mobileTB.addErrorStyleName("errorTextBox");
//				}
				
			}
			
			
			
			
			

			return valid;
		}

		private void submit() {
			
			
			kmrService.addCandidate(candidate, new AsyncCallback<Boolean>(){

				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					
				}

				public void onSuccess(Boolean result) {
					// TODO Auto-generated method stub
					
				}});
			
		}
	}
	
	@SuppressWarnings("deprecation")
	private void setUpCityOracle() {
		cityOracle = new MultiWordSuggestOracle();
		
		
		kmrService.getCitiesNames(countryLB.getItemText(countryLB.getSelectedIndex()), new AsyncCallback<CitiesNames>(){

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			public void onSuccess(CitiesNames result) {
				for (Iterator<String> iterator = result.names.iterator(); iterator
						.hasNext();) {
					String name = (String) iterator.next();
					cityOracle.add(name);
				}
				
			}});
		
		//create a new Suggest box with the new Oracle and add to the table again
		citySBox = new SuggestBox(cityOracle);
		citySBox.setValue("City");
		citySBox.addClickListener(new ClickListener(){
			public void onClick(Widget sender) {
				if(citySBox.getText().equals("City"))
					citySBox.setText("");
				
			}});
		table.setWidget(4, 2, citySBox);
	}

	private void setUpCompanyOracle() {
		companyOracle = new MultiWordSuggestOracle();
		
		kmrService.getComapniesNames(new AsyncCallback<CompaniesNames>() {

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			public void onSuccess(CompaniesNames result) {
				for (Iterator<String> iterator = result.names.iterator(); iterator
						.hasNext();) {
					String name = (String) iterator.next();
					companyOracle.add(name);
				}
				
			}
		});
	}
	
}
